<?php

namespace appApi\controllers;

use appApi\components\ResultStatus;
use appApi\dao\AppApi as AppApiDao;
use Yii;

/**
 * 处理接口方法请求
 * @package appApi\controllers
 */
class MethodController extends BaseApiController
{
    const REQUEST_TYPE = 'method';
    /**
     * @var \app\models\AccessToken 访问授权
     */
    private $accessToken;
    /**
     * 验证access_token
     * @return bool
     */
    protected function verifyToken()
    {
        $access = AppApiDao::accessTokenInfo($this->parameters->accessToken);
        if($access == false || $access->state != 1) {
            $this->sendError(ResultStatus::ACCESS_TOKEN_ERROR, 'access token错误.', true);
            Yii::error(ResultStatus::ACCESS_TOKEN_ERROR . 'access token错误., GET: ' . json_encode($_GET) . ', POST: ' . json_encode($_POST));
            return false;
        }
        $this->secretToken = $access->secret_token;
        $this->accessToken = $access;
        return true;
    }

    public function actionIndex()
    {
        $method = $this->parameters->method;
        // 获取方法处理配置信息
        $configUrl = Yii::$app->params['apiMethods'];
        $configUrl = str_replace(':?:',$this->parameters->version,$configUrl);
        if(!file_exists($configUrl)){
            $config = Yii::$app->params['apiMethodConfig'];//加载原始配置
        }else{
            $config = require($configUrl);
        }
        if(!isset($config[$method])) {
            return $this->sendError(ResultStatus::METHOD_NOT_EXIST, 'method不存在');
        }
        $classConfig = $config[$method];
        $classInstance = Yii::createObject($classConfig);
        $classInstance->setAccessToken($this->accessToken);
        $classInstance->setParameters($this->parameters);
        $classInstance->handle();
        $status = $classInstance->getStatus();
        if($status == ResultStatus::SUCCESS) {
            $result = $classInstance->getResult();
            return $this->sendResult($this->isNullToStr($result));
        } else {
            $error = $classInstance->getError();
            return $this->sendError($status, $error);
        }
    }
}